package com.heima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.heima.common.PageResult;
import com.heima.mapper.NodeMapper;
import com.heima.pojo.Business;
import com.heima.pojo.Node;
import com.heima.pojo.dto.NodeDto;
import com.heima.pojo.dto.PageNodeDto;
import com.heima.pojo.vo.NodeInfoVo;
import com.heima.pojo.vo.NodeVo;
import com.heima.service.NodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
@Slf4j
public class NodeServiceImpl implements NodeService {

    @Autowired
    private NodeMapper nodeMapper;

    /**
     * 搜索节点信息
     * @param pageRegionDto
     * @return
     */
    @Override
    public PageResult<NodeVo> searchRegionInfo(PageNodeDto pageRegionDto) {
        PageHelper.startPage(pageRegionDto.getPageIndex(), pageRegionDto.getPageSize());
        Page<NodeVo> list = nodeMapper.findByName(pageRegionDto);

        // 计算总页数
        int totalPage = (int) Math.ceil((double) list.getTotal() / pageRegionDto.getPageSize());
        return new PageResult<>(
                pageRegionDto.getPageIndex(),
                pageRegionDto.getPageSize(),
                totalPage,
                list.getTotal(),
                list.getResult()
        );
    }

    /**
     * 获取商圈类型
     * @return
     */
    @Override
    public List<Business> searchBusinessType() {
        return nodeMapper.getBusinessType();
    }

    /**
     * 添加节点
     * @param nodeDto
     * @return
     */
    @Override
    public Boolean saveNode(NodeDto nodeDto) {
        Node node = new Node();
        BeanUtils.copyProperties(nodeDto, node);
        Integer math = nodeMapper.insertNode(node);
        return math > 0;
    }

    /**
     * 获取节点下的vm列表
     * @param nodeId
     * @return
     */
    @Override
    public List<NodeInfoVo> getVmList(String nodeId) {
        return nodeMapper.getVmList(nodeId);
    }

    /**
     * 修改节点信息
     * @param nodeId
     * @param nodeDto
     * @return
     */
    @Override
    public Boolean updateNode(String nodeId, NodeDto nodeDto) {
        Node node = new Node();
        BeanUtils.copyProperties(nodeDto, node);
        Integer count = nodeMapper.updateNode(nodeId, node);
        return count > 0;
    }

    @Override
    public Boolean deleteNode(String nodeId) {
        // 如果点位下面还存在着vm则不允许删除
        Integer count = nodeMapper.countByNodeId(nodeId);
        if (count > 0) {
            throw new RuntimeException("该点位下有vm，不允许删除");
        }
        return nodeMapper.deleteNode(nodeId) > 0;
    }

    @Override
    public Integer queryNodeCount(Integer id) {
        return nodeMapper.queryNodeCount(id);
    }
}
